package com.example.administrator.testapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.Toast;
import com.example.AnReaderDemo.ZMUtility;
import com.example.AnReaderDemo.bean.LabelData;
import com.example.presenter.config.RFID_Config;
import com.rfid.api.ADReaderInterface;
import com.zmc.lib.zmlib;
import java.util.ArrayList;

/**
 * Created by Administrator on 2019/9/18 0018.
 */

public class AdminActivity extends Activity implements View.OnClickListener {

    LabelData labelData;
    RFID_Config rfid_config;

    private TabHost myTabhost = null;
    private Spinner sn_commType = null;// Connector  连接类型 串口 网口
    private Spinner sn_devName = null;// Device type  设备类型
    private EditText ed_ipAddr = null;// IP 网口
    private EditText ed_port = null;// Port 网口端口号
    private Spinner sn_comName = null;// com 串口地址
    private Spinner sn_comBaud = null;//波特率
    private Spinner sn_comFrame = null;//帧结构

    private Button btn_getDevInfo = null;// get device information
    private Button btn_setInventoryPara = null;// set para of inventory
    private Button btn_loadDefault = null;// Reset
    private Button btn_ReadFirmare = null;//Identification
    private Button btn_broadcast = null;

    static int INVENTORY_REQUEST_CODE = 1;// requestCode

    private int[] layRes = { R.id.tab_reader, R.id.tab_command, R.id.tab_inventory};

    private String[] layTittle = null;

    private int kno = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.admin_activity_main);

        rfid_config = new RFID_Config(this);

        String comName = rfid_config.GetHistoryString("COMNAME");

        int iDevIPorBaud = rfid_config.GetHistoryInt("COMBAUD");

        String comType = rfid_config.GetHistoryString("COMMTYPE");

        Toast.makeText(getApplicationContext(),
                "串口地址："+comName+"  波特率："+iDevIPorBaud+"  类型："+comType,
                Toast.LENGTH_SHORT).show();

        layTittle = new String[]{getString(R.string.tx_tab_device),
                getString(R.string.tx_tab_command),
                getString(R.string.tx_tab_inventory)
        };

        sn_commType = (Spinner) findViewById(R.id.sn_commType);
        sn_devName = (Spinner) findViewById(R.id.sn_devType);
        ed_ipAddr = (EditText) findViewById(R.id.ed_ipAddr);
        ed_port = (EditText) findViewById(R.id.ed_port);
        myTabhost = (TabHost) findViewById(R.id.tabhost);

        sn_comName = (Spinner) findViewById(R.id.sn_comName);
        sn_comBaud = (Spinner) findViewById(R.id.sn_comBaud);
        sn_comFrame = (Spinner) findViewById(R.id.sn_comFrame);
        btn_getDevInfo = (Button) findViewById(R.id.btn_getDevInfo);
        btn_setInventoryPara = (Button) findViewById(R.id.btn_paraInventory);
        btn_loadDefault = (Button) findViewById(R.id.btn_loadDefault);

        sn_commType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                CommTypeChange();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });

        // Load page
        myTabhost.setup();
        for (int i = 0; i < layRes.length; i++) {
            TabHost.TabSpec myTab = myTabhost.newTabSpec("tab" + i);
            myTab.setIndicator(layTittle[i]);
            myTab.setContent(layRes[i]);
            myTabhost.addTab(myTab);
        }

        myTabhost.setCurrentTab(0);

        // Get the Serial port
        ArrayList<CharSequence> m_comNameList = new ArrayList<CharSequence>();
        ArrayList<CharSequence> m_comBaudList = new ArrayList<CharSequence>();
        ArrayList<CharSequence> m_comFrameList = new ArrayList<CharSequence>();
        ArrayAdapter<CharSequence> m_adaComName = null;
        ArrayAdapter<CharSequence> m_adaComBaud = null;
        ArrayAdapter<CharSequence> m_adaComFrame = null;

        String m_comList[] = ADReaderInterface.GetSerialPortPath();
        int i = 0;
        for (String s : m_comList) {
            if (s.compareTo("/dev/ttyS1") == 0) {
                kno = i;
            }
            i++;
            m_comNameList.add(s);
        }

        m_comBaudList.add("9600");
        m_comBaudList.add("38400");
        m_comBaudList.add("57600");
        m_comBaudList.add("115200");

        m_comFrameList.add("8N1");
        m_comFrameList.add("8E1");
        m_comFrameList.add("8O1");

        m_adaComName = new ArrayAdapter<CharSequence>(this,
                android.R.layout.simple_spinner_dropdown_item, m_comNameList);
        m_adaComBaud = new ArrayAdapter<CharSequence>(this,
                android.R.layout.simple_spinner_dropdown_item, m_comBaudList);

        m_adaComFrame = new ArrayAdapter<CharSequence>(this,
                android.R.layout.simple_spinner_dropdown_item, m_comFrameList);

        sn_comName.setAdapter(m_adaComName);
        sn_comBaud.setAdapter(m_adaComBaud);
        sn_comFrame.setAdapter(m_adaComFrame);

        btn_getDevInfo.setOnClickListener(this);

        btn_loadDefault.setOnClickListener(this);
        btn_setInventoryPara.setOnClickListener(this);

        btn_getDevInfo.setEnabled(true); //false);

        btn_setInventoryPara.setEnabled(true); //false);

        btn_loadDefault.setEnabled(true); //false);

        btn_ReadFirmare = (Button) findViewById(R.id.btn_ReadFirmare);
        btn_ReadFirmare.setOnClickListener(this);
        btn_ReadFirmare.setEnabled(true);//Identification

        btn_broadcast = (Button) findViewById(R.id.btn_broadcast);
        btn_broadcast.setOnClickListener(this);
        btn_broadcast.setEnabled(true);//Search ip

        LoadActivityByHistory();
        //选择连接类型显示控件
        CommTypeChange();
    }

    //选择连接类型显示控件
    private void CommTypeChange() {
        RelativeLayout netView = (RelativeLayout) findViewById(R.id.group_net);
        RelativeLayout comView = (RelativeLayout) findViewById(R.id.group_com);
        switch (sn_commType.getSelectedItemPosition()) {
            case 0://COM
                netView.setVisibility(View.GONE);
                comView.setVisibility(View.VISIBLE);
                btn_broadcast.setVisibility(View.GONE);
                break;
            case 1://NET
                netView.setVisibility(View.VISIBLE);
                comView.setVisibility(View.GONE);
                btn_broadcast.setVisibility(View.VISIBLE);
                break;
            default:
                netView.setVisibility(View.GONE);
                comView.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void onClick(View v) {
        String str = "";
        switch (v.getId()) {
            //打开设备
            case R.id.btn_Save:
                SaveActivity();
                break;
            case R.id.btn_getDevInfo:// get the informatin of the device 设备信息
                rfid_config.GetInformation(true);//get version
                break;
            case R.id.btn_ReadFirmare:// 读写器标识
                GetReaderFlag();//get ident
                break;
            case R.id.btn_broadcast:
                //发广播查到设备IP
                str = RFID_Config.ZM_SendBorodBROADCAST_Getip();
                if (str.isEmpty()){

                }else{
                    String[] all = str.split(",");
                    ed_ipAddr.setText(all[0]);
                    ed_port.setText(all[1]);
                    rfid_config.MessageBox("提示", "搜索设备IP成功");
                }
                break;
            case R.id.btn_loadDefault:// reset  恢复出厂设置
                LoadFactoryDefault();
                break;
            case R.id.btn_paraInventory:
                GetParamAnt();
                break;

            default:
                break;
        }
    }

    //回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }
        if (requestCode != INVENTORY_REQUEST_CODE) {
            return;
        }
        Bundle bundle = data.getExtras();
        int iSize = bundle.getInt("CMDGetAntSize");
        byte[] m_nRecBuf = bundle.getByteArray("CMDGetAnt");
        if (0==iSize){
        }else {
            TestActivity.iScanLabel.SetParamAnt(m_nRecBuf, iSize);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //读写器标识
    private void GetReaderFlag(){
        int iret = -1;
        byte[] bufsnd = new byte[255];
        int[] isndsize = new int[2];
        byte[] bufrcv = new byte[255];
        int[] ircvsize = new int[2];
        byte[] bufret = new byte[255];
        int[] iretsize = new int[2];

        int itimeout = 500;
        int m_nNum = 0;

        bufsnd[m_nNum++] = (byte)labelData.CMDCOMMNUHEAD; //0xA5;
        bufsnd[m_nNum++] = 0x04;

        bufsnd[m_nNum++] = (byte)labelData.idevAddr[0];
        bufsnd[m_nNum++] = (byte)labelData.idevAddr[1];

        bufsnd[m_nNum++] = (byte) labelData.CMDGetReaderFlag; //命令字0x12

        bufsnd[m_nNum++] = ZMUtility.ZMAChecka(bufsnd, m_nNum);
        isndsize[0] = m_nNum;

        String str = "";
        isndsize[0]=6;
        iret = zmlib.ZMPacketData(labelData.fd[0], bufsnd, isndsize, bufrcv, ircvsize, bufret, iretsize, itimeout);
        if (iret >0){
            str = ZMUtility.bytes2HexString(bufret,iretsize[0]);
            new AlertDialog.Builder(this)
                    .setTitle(getString(R.string.tx_msg_getDevInfo))
                    .setMessage(str.toString())
                    .setPositiveButton(getString(R.string.tx_msg_certain), null)
                    .show();
        }else{
            new AlertDialog.Builder(this)
                    .setTitle(getString(R.string.tx_msg_getDevInfo))
                    .setMessage(
                            getString(R.string.tx_msg_getDevInfo_fail) + iret)
                    .setPositiveButton(getString(R.string.tx_msg_certain), null)
                    .show();
        }
    }//get ident

    //获取天线参数
    private  void GetParamAnt(){
        byte[] bufsnd = new byte[255];
        int[] isndsize = new int[2];
        byte[] bufrcv = new byte[255];
        int[] ircvsize = new int[2];
        byte[] bufret = new byte[255];
        int[] iretsize = new int[2];

        int itimeout = 500;
        int m_nNum = 0;

        bufsnd[m_nNum++] = (byte)labelData.CMDCOMMNUHEAD; //0xA5;
        bufsnd[m_nNum++] = 0x04;

        bufsnd[m_nNum++] = (byte)labelData.idevAddr[0];
        bufsnd[m_nNum++] = (byte)labelData.idevAddr[1];

        bufsnd[m_nNum++] =(byte) labelData.CMDGetAnt; //命令字0x73

        bufsnd[m_nNum++] = ZMUtility.ZMAChecka(bufsnd, m_nNum);
        isndsize[0] = m_nNum;

        zmlib.ZMPacketData(labelData.fd[0], bufsnd, isndsize, bufrcv, ircvsize, bufret, iretsize, itimeout);

        Intent intent = new Intent(this, InventorySetAntActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("CMDGetAntSize", ircvsize[0]);
        bundle.putByteArray("CMDGetAnt", bufrcv);
        intent.putExtras(bundle);
        startActivityForResult(intent, INVENTORY_REQUEST_CODE);
    }

    //恢复出厂设置
    private void LoadFactoryDefault(){
        int iret = -1;
        byte[] bufsnd = new byte[255];
        int[] isndsize = new int[2];
        byte[] bufrcv = new byte[255];
        int[] ircvsize = new int[2];
        byte[] bufret = new byte[255];
        int[] iretsize = new int[2];

        int itimeout = 4000;
        int m_nNum = 0;

        bufsnd[m_nNum++] = (byte)labelData.CMDCOMMNUHEAD; //0xA5;
        bufsnd[m_nNum++] = 0x04;

        bufsnd[m_nNum++] = (byte)labelData.idevAddr[0];
        bufsnd[m_nNum++] = (byte)labelData.idevAddr[1];

        bufsnd[m_nNum++] = (byte)labelData.CMDDefaultParam; ////(0x74) //恢复出厂值

        bufsnd[m_nNum++] = ZMUtility.ZMAChecka(bufsnd, m_nNum);
        isndsize[0] = m_nNum;

        String str;

        iret = zmlib.ZMPacketData(labelData.fd[0], bufsnd, isndsize, bufrcv, ircvsize, bufret, iretsize, itimeout);
        if (iret >0){
            str = "success";
            rfid_config.MessageBox(getString(R.string.tx_loadDefault), str);
        }else{
            new AlertDialog.Builder(this)
                    .setTitle(getString(R.string.tx_msg_getDevInfo))
                    .setMessage(
                            getString(R.string.tx_msg_getDevInfo_fail) + iret)
                    .setPositiveButton(getString(R.string.tx_msg_certain), null)
                    .show();
        }
    }

    //保存参数
    private void SaveActivity() {
        int devItem = 0;
        int commItem = 0;
        String ipStr = ed_ipAddr.getText().toString();
        String portStr = ed_port.getText().toString();
        int comNameItem = 0;
        int comBaudItem = 0;
        int comFrameItem = 0;

        if (!sn_devName.getAdapter().isEmpty()) {
            devItem = sn_devName.getSelectedItemPosition();
        }
        if (!sn_commType.getAdapter().isEmpty()) {
            commItem = sn_commType.getSelectedItemPosition();
        }
        if (!sn_comName.getAdapter().isEmpty()) {
            comNameItem = sn_comName.getSelectedItemPosition();
        }
        if (!sn_comBaud.getAdapter().isEmpty()) {
            comBaudItem = sn_comBaud.getSelectedItemPosition();
        }
        if (!sn_comFrame.getAdapter().isEmpty()) {
            comFrameItem = sn_comFrame.getSelectedItemPosition();
        }

        rfid_config.saveHistory("DEVNAME", devItem);
        rfid_config.saveHistory("COMMTYPE", commItem);
        rfid_config.saveHistory("COMBAUD", comBaudItem);
        rfid_config.saveHistory("COMFRAME", comFrameItem);
        rfid_config.saveHistory("COMNAME", comNameItem);
        rfid_config.saveHistory("DEVIPADDR", ipStr);
        rfid_config.saveHistory("DEVPORT", portStr);
        Toast.makeText(getApplicationContext(),"保存完成", Toast.LENGTH_SHORT).show();
    }

    //初始化参数，读出之前的值
    private void LoadActivityByHistory() {
        sn_devName.setSelection(1);

        int commItem = rfid_config.GetHistoryInt("COMMTYPE");
        if (commItem < sn_commType.getCount()) {
            sn_commType.setSelection(commItem);
        }

        sn_comName.setSelection(kno);

        int comBaudItem = rfid_config.GetHistoryInt("COMBAUD");
        if (comBaudItem < sn_comBaud.getCount() && comBaudItem >= 0) {
            sn_comBaud.setSelection(comBaudItem);
        }
        else {
            sn_comBaud.setSelection(1);
        }
        sn_comBaud.setSelection(3); //115200

        int comFrameItem = rfid_config.GetHistoryInt("COMFRAME");
        if (comFrameItem < sn_comFrame.getCount() && comFrameItem >= 0) {
            sn_comFrame.setSelection(comFrameItem);
        }
        else {
            sn_comFrame.setSelection(1);
        }
        sn_comFrame.setSelection(0);

        String sIp = rfid_config.GetHistoryString("DEVIPADDR");
        if (sIp != "") {
            ed_ipAddr.setText(sIp);
        }

        String sPort = rfid_config.GetHistoryString("DEVPORT");
        if (sPort != "") {
            ed_port.setText(sPort);
        }
    }

}